package com.hjwoo.app.utils;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

import com.hjwoo.app.R;
import com.hjwoo.app.common.LoanApplication;

import java.io.ByteArrayOutputStream;
import java.io.UnsupportedEncodingException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by liuderu on 2016/3/25.
 * 本类用于一些常用的基本运算
 */

public class Utils
{

    private static final String TAG = "Utils";

    public static int parseInt(String s, int defaultvalue)
    {
        int newint = 0;

        try
        {
            newint = Integer.parseInt(s);
        }
        catch (Exception e)
        {
            newint = defaultvalue;
        }

        return newint;
    }



//	private String QUERYADDRESS = "http://maps.googleapis.com/maps/api/geocode/json?latlng=%s,%s&sensor=true&language=zh_cn";
//
//	public String queryLocation(String lat, String lng) {
//		String url = String.format(QUERYADDRESS, lat, lng);
//		RequestParams params = new RequestParams(url);
//		ApiHttpClient.post(params, httpResponseHandler);
//
//
//		String result = ApiHttpClient.get(url, null);
//		String address = "未能查询到";
//		try {
//			JSONArray jsonArray = new JSONObject(result)
//					.getJSONArray("results");
//			if (jsonArray.length() > 1) {
//				JSONObject jsonObject = jsonArray.getJSONObject(0);
//				address = jsonObject.optString("formatted_address");
//				LoanLog.e("Add", address);
//			}
//
//		} catch (Exception e) {
//			// TODO: handle exception
//		}
//		return address;
//
//	}

    /**
     * 合并数组
     *
     * @param first
     * @param second
     * @param <T>
     * @return
     */
    public static <T> T[] concat(T[] first, T[] second)
    {
        T[] result = Arrays.copyOf(first, first.length + second.length);
        System.arraycopy(second, 0, result, first.length, second.length);
        return result;
    }

    /**
     * 转换成UTF-8
     *
     * @param str
     * @return String
     */
    public static String paseToUTF8(String str)
    {
        try
        {
            str = new String(str.getBytes(), "UTF-8");

        }
        catch (UnsupportedEncodingException e)
        {
            e.printStackTrace();
        }
        ;
        return str;
    }

    /**
     * 根据手机的分辨率从 dp 的单位 转成为 px(像素)
     */
    public static int dp2px(Context context, float dpValue)
    {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    // 获取ApiKey
//	public static String getMetaValue(Context context, String metaKey) {
//		Bundle metaData = null;
//		String apiKey = null;
//		if (context == null || metaKey == null) {
//			return null;
//		}
//		try {
//			ApplicationInfo ai = context.getPackageManager()
//					.getApplicationInfo(context.getPackageName(),
//							PackageManager.GET_META_DATA);
//			if (null != ai) {
//				metaData = ai.metaData;
//			}
//			if (null != metaData) {
//				apiKey = metaData.getString(metaKey);
//			}
//		} catch (PackageManager.NameNotFoundException e) {
//
//		}
//		return apiKey;
//	}

    /**
     * 设置手机网络类型，wifi，cmwap，ctwap，用于联网参数选择
     *
     * @return
     */
    static String getNetworkType()
    {
        String networkType = "wifi";
        ConnectivityManager manager = (ConnectivityManager) LoanApplication.getInstance()
            .getSystemService(Context.CONNECTIVITY_SERVICE);

        NetworkInfo netWrokInfo = manager.getActiveNetworkInfo();
        if (netWrokInfo == null || !netWrokInfo.isAvailable())
        {
            return ""; // 当前网络不可用
        }

        String info = netWrokInfo.getExtraInfo();
        if ((info != null)
            && ((info.trim().toLowerCase().equals("cmwap"))
                || (info.trim().toLowerCase().equals("uniwap"))
                || (info.trim().toLowerCase().equals("3gwap")) || (info
            .trim().toLowerCase().equals("ctwap"))))
        {
            // 上网方式为wap
            if (info.trim().toLowerCase().equals("ctwap"))
            {
                // 电信
                networkType = "ctwap";
            }
            else
            {
                networkType = "cmwap";
            }
        }
        return networkType;
    }

    /**
     * 检测网络是否可用
     *
     * @return
     */
    public static boolean isNetworkAvailable()
    {
        try
        {
            ConnectivityManager connectivityManager = (ConnectivityManager) LoanApplication.getInstance().getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo         networkInfo         = connectivityManager.getActiveNetworkInfo();
            return networkInfo != null && networkInfo.isAvailable() && networkInfo.isConnected();
        }
        catch (Exception e)
        {
            Log.v("ConnectivityManager", e.getMessage());
        }
        return false;
    }

    /**
     * 检测网络是否可用
     *
     * @param context
     * @return
     */
//	public static boolean isNetWorkConnected(Context context) {
//		if (context != null) {
//			ConnectivityManager mConnectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
//			NetworkInfo mNetworkInfo = mConnectivityManager.getActiveNetworkInfo();
//			if (mNetworkInfo != null) {
//				return mNetworkInfo.isAvailable();
//			}
//		}
//
//		return false;
//	}

    /**
     * 检测Sdcard是否存在
     *
     * @return
     */
    public static boolean isExitsSdcard()
    {
        if (android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED))
            return true;
        else
            return false;
    }

    static String getString(Context context, int resId)
    {
        return context.getResources().getString(resId);
    }

    /**
     * 设置标题
     *
     * @param titleStr
     * @param activity
     * @param isBackVisible
     */
    public static void initTitle(String titleStr, final Activity activity, boolean isBackVisible)
    {
        TextView textHeadTitle = (TextView) activity.findViewById(R.id.textHeadTitle);
        textHeadTitle.setText(titleStr);
        if (isBackVisible)
        {
            activity.findViewById(R.id.btnBack).setVisibility(View.VISIBLE);
            activity.findViewById(R.id.btnBack).setOnClickListener(new View.OnClickListener()
            {
                @Override
                public void onClick(View view)
                {
                    activity.finish();
                }
            });
        }
    }

    /**
     * 判断是不是手机号
     *
     * @param mobiles
     * @return
     */
    public static boolean isMobileNO(String mobiles)
    {
        Pattern p = Pattern
            .compile("^((13[0-9])|(15[^4,\\D])|(18[0,5-9]))\\d{8}$");
        Matcher m = p.matcher(mobiles);
        return m.matches();
     //   先关闭手机号验证
     //   return true;
    }

    /**
     * 验证身份证是否有效
     *
     * @param IDStr
     * @return String
     * @throws ParseException
     */
    @SuppressLint("SimpleDateFormat")
    public static boolean IDCardValidate(String IDStr)
    {

        boolean tipInfo = true;// 记录错误信息
        String  Ai      = "";

        // 判断号码的长度 15位或18位
        if (IDStr.length() != 15 && IDStr.length() != 18)
        {
            // tipInfo = "身份证号码长度应该为15位或18位。";
            tipInfo = false;
            return tipInfo;
        }

        // 18位身份证前17位位数字，如果是15位的身份证则所有号码都为数字
        if (IDStr.length() == 18)
        {
            Ai = IDStr.substring(0, 17);
        }
        else if (IDStr.length() == 15)
        {
            Ai = IDStr.substring(0, 6) + "19" + IDStr.substring(6, 15);
        }
        if (isNumeric(Ai) == false)
        {
            // tipInfo = "身份证15位号码都应为数字 ; 18位号码除最后一位外，都应为数字。";
            tipInfo = false;
            return tipInfo;
        }

        // 判断出生年月是否有效
        // String strYear = Ai.substring(6, 10);// 年份
        // String strMonth = Ai.substring(10, 12);// 月份
        // String strDay = Ai.substring(12, 14);// 日期
        // if (isDate(strYear + "-" + strMonth + "-" + strDay) == false) {
        // // tipInfo = "身份证出生日期无效。";
        // tipInfo = false;
        // return tipInfo;
        // }
        // GregorianCalendar gc = new GregorianCalendar();
        // SimpleDateFormat s = new SimpleDateFormat("yyyy-MM-dd");
        // try {
        // if ((gc.get(Calendar.YEAR) - Integer.parseInt(strYear)) > 150
        // || (gc.getTime().getTime() - s.parse(
        // strYear + "-" + strMonth + "-" + strDay).getTime()) < 0) {
        // // tipInfo = "身份证生日不在有效范围。";
        // tipInfo = false;
        // return tipInfo;
        // }
        // } catch (NumberFormatException e) {
        // e.printStackTrace();
        // } catch (java.text.ParseException e) {
        // e.printStackTrace();
        // }

        // if (Integer.parseInt(strMonth) > 12 || Integer.parseInt(strMonth) ==
        // 0) {
        // // tipInfo = "身份证月份无效";
        // tipInfo = false;
        // return tipInfo;
        // }
        // if (Integer.parseInt(strDay) > 31 || Integer.parseInt(strDay) == 0) {
        // // tipInfo = "身份证日期无效";
        // tipInfo = false;
        // return tipInfo;
        // }

        // 判断地区码是否有效
//		Hashtable<?, ?> areacode = GetAreaCode();
////         如果身份证前两位的地区码不在Hashtable，则地区码有误
//		if (areacode.get(Ai.substring(0, 2)) == null) {
//			// tipInfo = "身份证地区编码错误。";
//			tipInfo = false;
//			return tipInfo;
//		}
//
		if (isVarifyCode(Ai, IDStr) == false) {
        // tipInfo = "身份证校验码无效，不是合法的身份证号码";
        tipInfo = false;
        return tipInfo;
    }

        return tipInfo;
    }

    /*
     * 判断第18位校验码是否正确 第18位校验码的计算方式： 　　1. 对前17位数字本体码加权求和 　　公式为：S = Sum(Ai * Wi), i
     * = 0, ... , 16 　　其中Ai表示第i个位置上的身份证号码数字值，Wi表示第i位置上的加权因子，其各位对应的值依次为： 7 9 10 5
     * 8 4 2 1 6 3 7 9 10 5 8 4 2 　　2. 用11对计算结果取模 　　Y = mod(S, 11) 　　3.
     * 根据模的值得到对应的校验码 　　对应关系为： 　　 Y值： 0 1 2 3 4 5 6 7 8 9 10 　　校验码： 1 0 X 9 8 7 6
     * 5 4 3 2
     */
    private static boolean isVarifyCode(String Ai, String IDStr)
    {
        String[] VarifyCode = {
            "1", "0", "X", "9", "8", "7", "6", "5", "4",
            "3", "2"
        };
        String[] Wi = {
            "7", "9", "10", "5", "8", "4", "2", "1", "6", "3", "7",
            "9", "10", "5", "8", "4", "2"
        };
        int sum = 0;
        for (int i = 0; i < 17; i++)
        {
            sum = sum + Integer.parseInt(String.valueOf(Ai.charAt(i)))
                        * Integer.parseInt(Wi[i]);
        }
        int    modValue      = sum % 11;
        String strVerifyCode = VarifyCode[modValue];
        Ai = Ai + strVerifyCode;
        if (IDStr.length() == 18)
        {
            if (Ai.equals(IDStr) == false)
            {
                return false;

            }
        }
        return true;
    }

    /**
     * 判断字符串是否为数字,0-9重复0次或者多次
     *
     * @param strnum
     * @return
     */
    private static boolean isNumeric(String strnum)
    {
        Pattern pattern = Pattern.compile("[0-9]*");
        Matcher isNum   = pattern.matcher(strnum);
        if (isNum.matches())
        {
            return true;
        }
        else
        {
            return false;
        }
    }

    //验证密码长度
    public static boolean isPasswordValid(String password)
    {
        return password.length() > 4;
    }

    /**
     * 计算两个日期之间相差的天数
     *
     * @param smdate 较小的时间
     * @param bdate  较大的时间
     * @return 相差天数
     * @throws ParseException
     */
    public static int daysBetween(Date smdate, Date bdate)
    {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        try
        {
            smdate = sdf.parse(sdf.format(smdate));

            bdate = sdf.parse(sdf.format(bdate));
        }
        catch (ParseException e)
        {
            e.printStackTrace();
        }
        Calendar cal = Calendar.getInstance();
        cal.setTime(smdate);
        long time1 = cal.getTimeInMillis();
        cal.setTime(bdate);
        long time2        = cal.getTimeInMillis();
        long between_days = (time2 - time1) / (1000 * 3600 * 24);

        return Integer.parseInt(String.valueOf(between_days));
    }

    /**
     * 计算两个日期之间相差的天数 字符串的日期格式的计算
     *
     * @param smdate
     * @param bdate
     * @return 相差天数
     * @throws ParseException
     */
    public static int daysBetween(String smdate, String bdate)
    {
        SimpleDateFormat sdf   = new SimpleDateFormat("yyyy-MM-dd");
        Calendar         cal   = Calendar.getInstance();
        long             time1 = 0;
        try
        {
            cal.setTime(sdf.parse(smdate));
            time1 = cal.getTimeInMillis();
            cal.setTime(sdf.parse(bdate));
        }
        catch (ParseException e)
        {
            e.printStackTrace();
        }
        long time2        = cal.getTimeInMillis();
        long between_days = (time2 - time1) / (1000 * 3600 * 24);
        return Integer.parseInt(String.valueOf(between_days));
    }

    /**
     * 把日期转为字符串
     */
    public static String dataToString(Date date)
    {
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        return df.format(date);
    }
    /**
     * 把字符串转为日期
     */
    public static Date stringToDate(String strDate) throws Exception
    {
//        2016-07-18T13:24:14Z
        final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
        return sdf.parse(strDate);
    }

    /**
     * 将UTC时间转换为东八区时间
     * @param UTCTime
     * @return
     */
    public static String getLocalTimeFromUTC(String UTCTime){

         DateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss") ;
        Date UTCDate = null ;
        String localTimeStr = null ;
        try {
            UTCDate = format.parse(UTCTime);
            format.setTimeZone(TimeZone.getTimeZone("GMT+8")) ;
            localTimeStr = format.format(UTCDate) ;
        } catch (ParseException e) {
            e.printStackTrace();
        }

        return localTimeStr.replace("T"," ") ;
    }

    /* 将Server传送的UTC时间转换为指定时区的时间 */
    @SuppressLint("SimpleDateFormat")
    public static String converTime(String srcTime, TimeZone timezone) {
//        createdDate='2016-09-09T08: 48: 13Z',
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
//        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS");
        SimpleDateFormat dspFmt = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        String convertTime;
        Date result_date;
        long result_time = 0;
// 如果传入参数异常，使用本地时间
        if (null == srcTime) {
            result_time = System.currentTimeMillis();
        }else {

            try { // 将输入时间字串转换为UTC时间

                sdf.setTimeZone(TimeZone.getTimeZone("GMT00:00"));

                result_date = sdf.parse(srcTime);

                result_time = result_date.getTime();

            } catch (Exception e) { // 出现异常时，使用本地时间

                LoanLog.e("ee",e.toString());

                result_time = System.currentTimeMillis();

                dspFmt.setTimeZone(TimeZone.getDefault());

                convertTime = dspFmt.format(result_time);

                return convertTime;

            }

        }
        // 设定时区
        dspFmt.setTimeZone(timezone);
        convertTime = dspFmt.format(result_time);
        return convertTime;
    }


    /**
     * 把bitmap转成base64
     * @param bitmap
     * @return String
     */
    public static String bitmapToString(Bitmap bitmap)
    {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 60, baos);
        byte[] b = baos.toByteArray();
        return Base64.encodeToString(b, Base64.DEFAULT);
    }

    /**
     * 压缩图片
     *
     * @param bitmap
     * @return
     */
    public static Bitmap small(Bitmap bitmap)

    {
        Matrix matrix = new Matrix();
        matrix.postScale(0.3f, 0.3f); //长和宽放大缩小的比例
        Bitmap resizeBmp = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
        return resizeBmp;
    }

}
